package com.llap.exp190929.controller;

import com.llap.exp190929.dto.PaginatedDto;
import com.llap.exp190929.entity.Book;
import com.llap.exp190929.error.BadRequestException;
import com.llap.exp190929.error.ConflictException;
import com.llap.exp190929.error.RestException;
import com.llap.exp190929.error.UnauthorizedException;
import com.llap.exp190929.service.BookService;
import com.llap.exp190929.util.Util;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
@RestController
@RequestMapping("books")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class BooksController {
    private BookService bookService;

    @GetMapping("")
    public PaginatedDto<Book> findBooks(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize,
            @RequestParam(required = false, defaultValue = "-1") Integer type,
            @RequestParam(required = false, defaultValue = "") String name,
            @RequestParam(required = false, defaultValue = "0,1") String state) {
        String[] s = state.split(",");
        int[] states = new int[s.length];
        for (int i = 0; i < s.length; ++i) states[i] = Integer.parseInt(s[i]);
//        System.out.println(Arrays.toString(states));
//        System.out.println(name);
//        System.out.println(type);
        return PaginatedDto.from(bookService.findBooks(page, pageSize, type, name, states));
    }

    @GetMapping("{id}")
    public Book findBook(@PathVariable Integer id) {
        return bookService.findBook(id);
    }

    @PostMapping("")
    public Book addBook(@RequestBody Book book) throws RestException {
        if (bookService.findBook(book.getCode()) != null) throw new ConflictException("Code already exists");
        if (book.getCode().isEmpty() || book.getName().isEmpty()) throw new BadRequestException("Parameters required");
        return bookService.addBook(book);
    }

    @DeleteMapping("")
    public void deleteBook(@RequestParam Integer id) throws RestException {
        if (Util.isAdmin(Util.getLoginUser())) bookService.deleteBook(id);
        else throw new UnauthorizedException("");
    }

    @PatchMapping("")
    public Book updateBook(@RequestBody Book book) throws RestException {
        Book original = bookService.findBook(book.getCode());
        if (original != null && !original.getId().equals(book.getId())) throw new ConflictException("Code already exists");
        return bookService.updateBook(book);
    }
}
